package com.wxmit.base.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.wxmit.base.constant.ShushanConstants;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * @author huangxiong
 * @date 2024/04/02 10:06
 */
public class ThreadMdcUtil {
    public static final String TRACE_ID = "TRACE_ID";

    private static final Snowflake snowflake;

    static {
        snowflake = IdUtil.getSnowflake(1, 1);
    }


    // 获取唯一性标识
    public static String generateTraceId() {
        return snowflake.nextIdStr();
    }

    public static void setTraceIdIfAbsent() {
        if (MDC.get(TRACE_ID) == null) {
            MDC.put(TRACE_ID, generateTraceId());
        }
    }

    public static void setTraceIdIfNull(String traceId) {
        MDC.put(TRACE_ID , Objects.isNull(traceId) ? generateTraceId() : traceId);
    }
    public static void removeTraceId() {
        MDC.remove(TRACE_ID);
    }
    public static String getTraceId(){
        return MDC.get(TRACE_ID);
    }

    /**
     * 用于父线程向线程池中提交任务时，将自身MDC中的数据复制给子线程
     * @author freedom
     * @date 2022/12/28 17:52
     * @param callable callable
     * @param context  context
     * @return {@link Callable<T>}
     */
    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }


    /**
     * 用于父线程向线程池中提交任务时，将自身MDC中的数据复制给子线程
     * @author freedom
     * @date 2022/12/28 17:52
     * @param runnable runnable
     * @param context  context
     * @return {@link Runnable}
     */
    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }



}
